package itbour.onetouchshow.activity.main;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.umeng.analytics.game.UMGameAgent;
import com.ys.uilibrary.tab.BottomTabView;
import com.ys.uilibrary.vp.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.login.LoginActivity;
import itbour.onetouchshow.base.BaseApplication;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.bean.AdDialogInfo;
import itbour.onetouchshow.bean.AppBanner;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.fragment.design.DesignFragment;
import itbour.onetouchshow.fragment.home.HomeFragment;
import itbour.onetouchshow.fragment.me.MeFragment;
import itbour.onetouchshow.observable.NetWorkObservable;
import itbour.onetouchshow.singlecase.InchingDataSingleCase;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.SpUtils;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.sharedpreference.PreferencesHelper;
import itbour.onetouchshow.view.ActivityUtils;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class MainActivity extends MVPBaseActivity<MainContract.View, MainPresenter> implements MainContract.View, NetWorkObservable.NetWorkObserver {

    private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
    @BindView(R.id.viewPager)
    public NoScrollViewPager viewPager;
    @BindView(R.id.bottomTabView)
    public BottomTabView bottomTabView;
    @BindView(R.id.id_layout_no_network)
    public LinearLayout layout_no_network;
    @BindView(R.id.error_view)
    public LinearLayout errorView;
    public boolean isFrist = true;
    public int currentSlectIndex = -1;
    public MainPresenter mPresenter = new MainPresenter(this);
    protected FragmentPagerAdapter adapter;
    protected ArrayList<Fragment> fragments = new ArrayList<>();
    protected ArrayList<BottomTabView.TabItemView> tabItemViews = new ArrayList<>();
    protected String[] titles = new String[]{"玩大片", "搞设计", "冲顶大赛", "我的"};
    protected int currentPageIndex = -1;
    Fragment homeFrg, design, meFrg;
    //记录用户首次点击返回键的时间
    private long firstTime = 0;

    @Override
    public void loadSucceed(String result) {
        viewPager.setVisibility(View.VISIBLE);
        layout_no_network.setVisibility(View.GONE);
        errorView.setVisibility(View.GONE);
        // requestPermission();
    }


    @Override
    public void loadFaild(String error) {
        T_.showToastReal(error);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //   L_.e("异常 onSaveInstanceState " + currentSlectIndex);
        outState.putInt("currentSlectIndex", currentSlectIndex);
    }


    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        SpUtils.getInstance().saveBoolean("isFirst", false);
        if (mPresenter == null) {
            mPresenter = new MainPresenter(this);
        }
        // showLoadingView();
        BaseApplication.instance().registerNetWorkObserver(this);
        mPresenter.getAppBannerInfo();
        mPresenter.getHomeDetailsData();
//        setImmersionBarBlack();
        //showLoadingView();
        initButtomTab(savedInstanceState);
        initParams();

    }

    @Override
    protected void initTitle() {
        ImmersionBar.with(this).transparentStatusBar().init();
    }

    protected void initButtomTab(Bundle savedInstanceState) {
        bottomTabView.setTabItemViews(getTabViews());
        if (getOnTabItemSelectListener() != null) {
            bottomTabView.setOnTabItemSelectListener(getOnTabItemSelectListener());
        }
        bottomTabView.setOnSecondSelectListener(new BottomTabView.OnSecondSelectListener() {
            @Override
            public void onSecondSelect(int position) {

            }
        });

        if (savedInstanceState != null) {
            currentSlectIndex = savedInstanceState.getInt("currentSlectIndex");
            // L_.e("异常 afterCreate+  " + currentSlectIndex);
            if (bottomTabView != null && currentPageIndex != -1) {
                bottomTabView.updatePosition(currentSlectIndex);
                viewPager.setCurrentItem(currentSlectIndex, false);
            }

        }

    }

    protected List<Fragment> getFragments() {
        fragments = new ArrayList<>();
        fragments.add(homeFrg);
        fragments.add(design);
        //fragments.add(groupFrg);
        fragments.add(meFrg);
        return fragments;
    }

    @Override
    public void initView() {
    }

    protected List<BottomTabView.TabItemView> getTabViews() {
        BottomTabView.TabItemView tabItemView1 = new BottomTabView.TabItemView(this, titles[0], R.color.tab_normal, R.color.tab_selected, R.drawable.tab_paly_video_normal, R.drawable.tab_paly_video_selector);
        tabItemViews.add(tabItemView1);
        BottomTabView.TabItemView tabItemView2 = new BottomTabView.TabItemView(this, titles[1], R.color.tab_normal, R.color.tab_selected, R.drawable.tab_paly_desgin_normal, R.drawable.tab_paly_desgin_seletor);
        tabItemViews.add(tabItemView2);

        //BottomTabView.TabItemView tabItemView3 = new BottomTabView.TabItemView(this, titles[2], R.color.tab_normal, R.color.tab_selected, R.drawable.tab_find_normal, R.drawable.tab_find_selector);
        //tabItemViews.add(tabItemView3);
        BottomTabView.TabItemView tabItemView4 = new BottomTabView.TabItemView(this, titles[2], R.color.tab_normal, R.color.tab_selected, R.drawable.tab_me_normal, R.drawable.tab_me_seletor);
        tabItemViews.add(tabItemView4);
        return tabItemViews;
    }

    public void initParams() {
        homeFrg = new HomeFragment();
        design = new DesignFragment();
        //groupFrg = new HomeFragment(playLargeList);
        meFrg = new MeFragment();
        //设置ViewPager的缓存界面数,默认缓存为2
        viewPager.setOffscreenPageLimit(2);
        adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return getFragments().get(position);
            }

            @Override
            public int getCount() {
                return getFragments().size();
            }
        };

        viewPager.setAdapter(adapter);
        if (getOnPageChangeListener() != null) {
            viewPager.addOnPageChangeListener(getOnPageChangeListener());
        }
    }

    protected ViewPager.OnPageChangeListener getOnPageChangeListener() {
        return new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                currentSlectIndex = position;
                bottomTabView.updatePosition(position);
                getToolBarView().setTitleText(titles[position]);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AppConst.CURRENT_ME != -1 && App.isLogin()) {
            L_.e("AppConst.CURRENT_ME" + AppConst.CURRENT_ME);
            bottomTabView.updatePosition(AppConst.CURRENT_ME);
            viewPager.setCurrentItem(AppConst.CURRENT_ME, false);
            AppConst.CURRENT_ME = -1;
        }
        // 集成基本统计分析,初始化 Session
        UMGameAgent.onResume(getApplication());
    }

    @Override
    public void onPause() {
        super.onPause();
        // //集成基本统计分析, 结束 Session
        UMGameAgent.onPause(getApplication());
    }

    public View getCenterView() {
        return null;
    }

    public BottomTabView.OnTabItemSelectListener getOnTabItemSelectListener() {
        return new BottomTabView.OnTabItemSelectListener() {
            @Override
            public void onTabItemSelect(int position) {
                currentSlectIndex = position;
                if (App.isLogin()) {
                    viewPager.setCurrentItem(position, true);
                } else {
                    if (position == 2) {
                        currentPageIndex = viewPager.getCurrentItem();
                        bottomTabView.updatePosition(currentPageIndex);
                        if (AppConst.CURRENT_PAGE == -1) {
                            AppConst.CURRENT_PAGE = 0;
                        }
                        AppConst.CURRENT_ME = position;
                        openActivity(LoginActivity.class);
                    } else {
                        viewPager.setCurrentItem(position, true);
                        AppConst.CURRENT_PAGE = position;
                        AppConst.CURRENT_ME = -1;
                    }
                }

            }
        };
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {
                    T_.showToastReal("再按一次退出程序");
                    firstTime = secondTime;
                    return true;
                } else {
                    ActivityUtils.removeAllActivity();
                    System.exit(0);
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApplication.instance().unregisterNetWorkObserver(this);
    }


    @Override
    public void loadBannerSuccess(String result) {
        AppBanner appBanner = new Gson().fromJson(result, AppBanner.class);
        InchingDataSingleCase.INSTANCE.setAppBanner(appBanner);
    }

    @Override
    public void getAdDialogInfoSuccess(String response) {
        AdDialogInfo adDialogInfo = new Gson().fromJson(response, AdDialogInfo.class);
        PreferencesHelper.saveData(AppConst.KEY_DIALOG_INFO, adDialogInfo);
        if (adDialogInfo.getDisplayType() == 1 || adDialogInfo.getDisplayType() == 3) {
            showAdDialog(adDialogInfo);
        }
    }


    @Override
    public void onNetWorkStatusChange(boolean b) {

    }

    @Override
    public void onNewWorkEnvironment(NetWorkObservable.NetStateChangeEvent.NetState netState) {

    }
}
